package com.runtu.domain.trade.service.lock.filter;

import com.runtu.domain.trade.adapter.repository.ITradeRepository;
import com.runtu.domain.trade.model.entity.GroupBuyActivityEntity;
import com.runtu.domain.trade.model.entity.TradeLockRuleCommandEntity;
import com.runtu.domain.trade.model.entity.TradeLockRuleFilterBackEntity;
import com.runtu.domain.trade.service.lock.factory.TradeLockRuleFilterFactory;
import com.runtu.types.design.framework.link.model2.handler.ILogicHandler;
import com.runtu.types.enums.ActivityStatusEnumVO;
import com.runtu.types.enums.ResponseCode;
import com.runtu.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @ClassName ActivityUsabilityRuleFilter
 * @Description 活动状态时间的过滤----活动的可用性，规则过滤【状态、有效期】
 * @date 2025/8/11 14:10
 * @Version 1.0
 */
@Slf4j
@Service
public class ActivityUsabilityRuleFilter implements ILogicHandler<TradeLockRuleCommandEntity, TradeLockRuleFilterFactory.DynamicContext, TradeLockRuleFilterBackEntity> {

    @Resource
    private ITradeRepository tradeRepository;

    /**
     * 受理，查询活动 做一下活动的过滤操作
     * @param requestParameter
     * @param dynamicContext
     * @return
     * @throws Exception
     */
    @Override
    public TradeLockRuleFilterBackEntity apply(TradeLockRuleCommandEntity requestParameter, TradeLockRuleFilterFactory.DynamicContext dynamicContext) throws Exception {
        log.info("交易规则过滤-活动的可用性校验{} activityId:{}", requestParameter.getUserId(), requestParameter.getActivityId());

        //主要要做的就是把活动信息查询出来 然后去活动信息中做一些判断 判断这个信息
        /*1、通过活动id去查询活动信息 返回的结果增加一个实体类来返回 GroupBuyActivityEntity*/
        GroupBuyActivityEntity groupBuyActivity= tradeRepository.queryGroupBuyActicityByActivityId(requestParameter.getActivityId());

        /*2、校验活动状态*/
        if(!groupBuyActivity.getStatus().equals(ActivityStatusEnumVO.EFFECTIVE)){
            throw new AppException(ResponseCode.E0101);
        }
        Date currentDate = new Date();
        if (currentDate.before(groupBuyActivity.getStartTime()) || currentDate.after(groupBuyActivity.getEndTime())){
            throw new AppException(ResponseCode.E0102);
        }

        /*3、写道上下文中*/
        dynamicContext.setGroupBuyActivity(groupBuyActivity);

        return next(requestParameter,dynamicContext);
    }
}
